from flask import Flask, request, redirect, jsonify
import uuid

app = Flask(__name__)

# 模拟用户数据库
users = {
    "user1": "password1"
}

# 模拟授权码和令牌数据库
authorization_codes = {}
access_tokens = {}

# 登录接口
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        if username in users and users[username] == password:
            # 登录成功，返回门户页面
            return '''
                <h1>Welcome to the portal page!</h1>
                <a href='/authorize?client_id=client1&redirect_uri=http://192.168.6.128:5001/callback1'>Access Third Party Sub - Function 1</a><br>
                <a href='/authorize?client_id=client2&redirect_uri=http://192.168.6.128:5002/callback2'>Access Third Party Sub - Function 2</a>
            '''
        else:
            return "Invalid username or password"
    return '''
        <form method="post">
            <input type="text" name="username" placeholder="Username">
            <input type="password" name="password" placeholder="Password">
            <input type="submit" value="Login">
        </form>
    '''

# 授权接口
@app.route('/authorize')
def authorize():
    client_id = request.args.get('client_id')
    redirect_uri = request.args.get('redirect_uri')
    # 生成授权码
    code = str(uuid.uuid4())
    authorization_codes[code] = {
        "client_id": client_id,
        "redirect_uri": redirect_uri
    }
    # 重定向到三方系统，并附带授权码
    return redirect(f"{redirect_uri}?code={code}")

# 获取令牌接口
@app.route('/token', methods=['POST'])
def token():
    code = request.form.get('code')
    if code in authorization_codes:
        # 生成访问令牌
        access_token = str(uuid.uuid4())
        access_tokens[access_token] = authorization_codes[code]
        del authorization_codes[code]
        return jsonify({
            "access_token": access_token,
            "token_type": "Bearer"
        })
    return jsonify({"error": "Invalid authorization code"}), 400

# 获取用户信息接口
@app.route('/userinfo')
def userinfo():
    access_token = request.headers.get('Authorization').replace('Bearer ', '')
    if access_token in access_tokens:
        return jsonify({
            "username": "user1"
        })
    return jsonify({"error": "Invalid access token"}), 401

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=5000)